﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Crm.Workflow;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using System.Net;
using System.IO;

namespace CrmContrib.Workflow.Activities.Networking
{
    [CrmWorkflowActivity("Download File", "CrmContrib \\ Networking")]
    public class DownloadFileActivity : Activity
    {
        [CrmInput("Url")]
        [ValidationOption(ValidationOption.Required)]
        public string Url
        {
            get { return (string)base.GetValue(DownloadFileActivity.UrlProperty); }
            set { base.SetValue(DownloadFileActivity.UrlProperty, value); }
        }

        public static readonly DependencyProperty UrlProperty = DependencyProperty.Register("Url", typeof(string), typeof(DownloadFileActivity));

        [CrmOutput("File ID")]
        public string FileID
        {
            get { return (string)base.GetValue(DownloadFileActivity.FileIDProperty); }
            set { base.SetValue(DownloadFileActivity.FileIDProperty, value); }
        }

        public static readonly DependencyProperty FileIDProperty = DependencyProperty.Register("FileID", typeof(string), typeof(DownloadFileActivity));

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            var client = new WebClient();
            client.UseDefaultCredentials = true;

            var data = client.DownloadData(this.Url);
            var entry = FileRegistry.AddFile(data);
            this.FileID = entry.FileID.ToString();

            return base.Execute(executionContext);
        }
    }
}
